package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atguigu.spzx.manager.constant.CacheConstant;
import com.atguigu.spzx.manager.service.ValidateCodeService;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    /**
     {
     "code": 200,
     "message": "操作成功",
     "data": {
     "codeKey": "ee179eb067c54e898b5cf8b2430236f8",
     "codeValue": ""
     }
     }
     * @return
     */
    @Override
    public ValidateCodeVo generateValidateCode() {
        //1.生成验证码
        // 使用hutool工具包中的工具类生成图片验证码
        //参数：宽  高  验证码位数 干扰线数量
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        String codeValue = circleCaptcha.getCode(); //验证码:例如   1234
        String imageBase64 = circleCaptcha.getImageBase64();  //验证码图片，base64编码 字符串

        //2.将验证码存储到redis中
        String codeKay = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX+codeKay,codeValue,5, TimeUnit.MINUTES);

        //3.封装数据
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(codeKay);
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64); // <img src=""/>

        //4.返回数据
        return validateCodeVo;
    }
}
